 import javax.swing.*;

public class HardDisk
{
    public DiskPlatter platter;
    public DiskScheduler diskScheduler;
    public Viewer viewer;
    
    public int trackNumber = 10;
    public int sectorNumber = 15;
    
    public int headTrack;
    public int headSector;
    
    public int targetTrack=-1;
    public int targetSector=-1;
    
    public int trackMovement=0;
    public boolean readingBlock=false;
    
    public HardDisk()
    {
        platter = new DiskPlatter(trackNumber,sectorNumber);
        diskScheduler = new NCQ(this);
        viewer = new Viewer(this);
    }
    
    public void addRequest(Request r)
    {
        platter.addRequest(r);
        diskScheduler.addRequest(r);
    }
    
    public void removeRequest(Request r)
    {
        platter.removeRequest(r);
        diskScheduler.removeRequest(r);
    }
    
    public void tick()
    {
        diskScheduler.tick();
        
        if(targetTrack>=0 && targetTrack<trackNumber)
        {
            if(headTrack < targetTrack)
            {
                trackMovement = 1;
            }
            else if(headTrack > targetTrack)
            {
                trackMovement = -1;
            }
            else
            {
                trackMovement = 0;
                
                if(headSector==targetSector)
                {
                    readingBlock = true;    
                }
            }
        }
        
        if(readingBlock)
        {
            readingBlock=false;
            removeRequest(new Request(headTrack, headSector));
        }
        else
        {
            headSector++;
            if(headSector>=sectorNumber)
                headSector=0;
            
            headTrack = headTrack+trackMovement;
            if(headTrack>=trackNumber)
            {
                headTrack = trackNumber-1;
            }
            if(headTrack< 0)
            {
                headTrack=0;
            }
        }
    
        viewer.repaint();
    }
    
    public static void main(String args[])
    {
        HardDisk hd = new HardDisk();
        
        JFrame frame = new JFrame("harddisk");
        frame.setSize(800, 600);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(hd.viewer);
        frame.validate();
        
        TimeManager tm = new TimeManager(hd);
        tm.start();
    }
}
